﻿using AJWPFAdmin.Modules.Main.Views;
using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services;
using AJWPFAdmin.Services.EF;
using Masuit.Tools.Models;
using MaterialDesignExtensions.Controls;
using MaterialDesignThemes.Wpf;
using Microsoft.EntityFrameworkCore;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using AJWPFAdmin.Core.Validation;
using Masuit.Tools;
using AJWPFAdmin.Core.Enums;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using AJWPFAdmin.Core;
using Masuit.Tools.Systems;
using Newtonsoft.Json;
using AJWPFAdmin.Core.Components.AJFilePicker.ViewModels;
using AJWPFAdmin.Core.ExtensionMethods;
using Prism.Ioc;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using Masuit.Tools.DateTimeExt;
using LiveChartsCore.SkiaSharpView.WPF;
using System.Windows;
using LiveChartsCore.VisualElements;
using LiveChartsCore.SkiaSharpView.VisualElements;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using System.Windows.Media;
using AJWPFAdmin.Core.Mvvm;
using AJWPFAdmin.Core.Models.EF.Tables;
using MaterialDesignExtensions.Model;
using System.Windows.Controls;
using Yitter.IdGenerator;
using AJWPFAdmin.Services.EF.TableExts;
using AJWPFAdmin.Core.Components.ViewModels;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Core.Models;
using DocumentFormat.OpenXml.Spreadsheet;
using AJWPFAdmin.Services.Models;
using System.IO;

namespace AJWPFAdmin.Modules.Main.ViewModels
{
    public class ShippingRecordFormViewModel : AnnotationValidationViewModel, IDialogAware
    {


        private string _dialogTitle;
        public string DialogTitle
        {
            get { return _dialogTitle; }
            set { SetProperty(ref _dialogTitle, value); }
        }

        private UploadConfig _uploadOptions;
        public UploadConfig UploadOptions
        {
            get
            {
                return _uploadOptions;
            }
            set
            {
                SetProperty(ref _uploadOptions, value);
            }
        }

        private UploadConfig _carInfoUploadOptions;
        public UploadConfig CarInfoUploadOptions
        {
            get
            {
                return _carInfoUploadOptions;
            }
            set
            {
                SetProperty(ref _carInfoUploadOptions, value);
            }
        }

        private bool _imageTypeSelectorShow;
        public bool ImageTypeSelectorShow
        {
            get { return _imageTypeSelectorShow; }
            set { SetProperty(ref _imageTypeSelectorShow, value); }
        }

        private string _selectedImageType;
        public string SelectedImageType
        {
            get { return _selectedImageType; }
            set
            {
                if (SetProperty(ref _selectedImageType, value))
                {
                    ConfirmImageTypeCmd?.RaiseCanExecuteChanged();
                }
            }
        }

        private Dictionary<string, Func<string>> _imageTypeOptions;
        public Dictionary<string, Func<string>> ImageTypeOptions
        {
            get { return _imageTypeOptions; }
            set { SetProperty(ref _imageTypeOptions, value); }
        }

        private bool _saving;
        public bool Saving
        {
            get { return _saving; }
            set { SetProperty(ref _saving, value); }
        }

        private bool _loading;
        public bool Loading
        {
            get { return _loading; }
            set { SetProperty(ref _loading, value); }
        }

        #region 车辆字段

        private string _verifiedLoadWeight;
        /// <summary>
        /// 核定载重质量
        /// </summary>
        public string VerifiedLoadWeight
        {
            get
            {
                return _verifiedLoadWeight;
            }
            set
            {
                SetProperty(ref _verifiedLoadWeight, value);
            }
        }

        private string _permittedTowingWeight;
        /// <summary>
        /// 准牵引总质量
        /// </summary>
        public string PermittedTowingWeight
        {
            get
            {
                return _permittedTowingWeight;
            }
            set
            {
                SetProperty(ref _permittedTowingWeight, value);
            }
        }

        private ObservableCollection<UploadFileItem> _carImage;
        public ObservableCollection<UploadFileItem> CarImage
        {
            get { return _carImage; }
            set
            {
                SetProperty(ref _carImage, value);
            }
        }

        private ObservableCollection<UploadFileItem> _nameplate;
        public ObservableCollection<UploadFileItem> Nameplate
        {
            get { return _nameplate; }
            set
            {
                SetProperty(ref _nameplate, value);
            }
        }

        private ObservableCollection<UploadFileItem> _engineNameplate;
        public ObservableCollection<UploadFileItem> EngineNameplate
        {
            get { return _engineNameplate; }
            set
            {
                SetProperty(ref _engineNameplate, value);
            }
        }

        private ObservableCollection<UploadFileItem> _machineEnvProtectionLabel;
        public ObservableCollection<UploadFileItem> MachineEnvProtectionLabel
        {
            get { return _machineEnvProtectionLabel; }
            set
            {
                SetProperty(ref _machineEnvProtectionLabel, value);
            }
        }

        private ObservableCollection<UploadFileItem> _attachments;
        public ObservableCollection<UploadFileItem> Attachments
        {
            get { return _attachments; }
            set
            {
                SetProperty(ref _attachments, value);
            }
        }

        private ObservableCollection<UploadFileItem> _emissionStandardImages;
        public ObservableCollection<UploadFileItem> EmissionStandardImages
        {
            get { return _emissionStandardImages; }
            set
            {
                SetProperty(ref _emissionStandardImages, value);
            }
        }

        private ObservableCollection<UploadFileItem> _vehicleLicense;
        public ObservableCollection<UploadFileItem> VehicleLicense
        {
            get { return _vehicleLicense; }
            set
            {
                SetProperty(ref _vehicleLicense, value);
            }
        }


        private string _carBrandModel;
        [Display(Name = "品牌型号")]
        [StringLength(50, ErrorMessage = "{0}超长:{1}")]
        public string CarBrandModel
        {
            get { return _carBrandModel; }
            set
            {
                SetProperty(ref _carBrandModel, value);
            }
        }

        private string _carNo;

        public string CarNo
        {
            get { return _carNo; }
            set
            {
                SetProperty(ref _carNo, value);
                SaveCmd.RaiseCanExecuteChanged();
            }
        }

        private CarPlateColor _plateColor;
        /// <summary>
        /// 号牌颜色
        /// </summary>
        public CarPlateColor PlateColor
        {
            get { return _plateColor; }
            set
            {
                SetProperty(ref _plateColor, value);
            }
        }

        private EmissionStandard _emissionStandard;
        /// <summary>
        /// 排放标准
        /// </summary>
        public EmissionStandard EmissionStandard
        {
            get { return _emissionStandard; }
            set
            {
                SetProperty(ref _emissionStandard, value);
            }
        }

        private DateTime? _expireDate;
        public DateTime? ExpireDate
        {
            get { return _expireDate; }
            set
            {
                SetProperty(ref _expireDate, value);
            }
        }

        private AJTableFormSchemaItemOptions _fuelTypeCode;
        /// <summary>
        /// 燃料类型编码
        /// </summary>
        public AJTableFormSchemaItemOptions FuelTypeCode
        {
            get { return _fuelTypeCode; }
            set
            {
                SetProperty(ref _fuelTypeCode, value);
            }
        }

        private bool _networkingStatus;
        /// <summary>
        /// 联网状态
        /// </summary>
        public bool NetworkingStatus
        {
            get { return _networkingStatus; }
            set
            {
                SetProperty(ref _networkingStatus, value);
            }
        }

        private DateTime? _regDate;
        /// <summary>
        /// 注册日期
        /// </summary>
        public DateTime? RegDate
        {
            get { return _regDate; }
            set
            {
                SetProperty(ref _regDate, value);
            }
        }

        private string _teamName;
        /// <summary>
        /// 车队名称
        /// </summary>
        [Display(Name = "车队名称")]
        [StringLength(50, ErrorMessage = "{0}超长:{1}")]
        public string TeamName
        {
            get { return _teamName; }
            set
            {
                SetProperty(ref _teamName, value);
            }
        }

        private AJTableFormSchemaItemOptions _truckTypeCode;
        /// <summary>
        /// 货车车辆类型编码, SystemDictionary.Code
        /// </summary>
        [Display(Name = "货车类型")]
        public AJTableFormSchemaItemOptions TruckTypeCode
        {
            get { return _truckTypeCode; }
            set
            {
                SetProperty(ref _truckTypeCode, value);
            }
        }

        private AJTableFormSchemaItemOptions _usageDescCode;
        /// <summary>
        /// 使用性质编号
        /// </summary>
        [Display(Name = "使用性质")]
        public AJTableFormSchemaItemOptions UsageDescCode
        {
            get { return _usageDescCode; }
            set
            {
                SetProperty(ref _usageDescCode, value);
            }
        }


        private string _vin;
        [Display(Name = "VIN")]
        [StringLength(50, ErrorMessage = "{0}超长")]
        public string VIN
        {
            get { return _vin; }
            set
            {
                SetProperty(ref _vin, value);
            }
        }

        #endregion

        private ShippingRecord _form;
        public ShippingRecord Form
        {
            get => _form;
            set
            {
                SetProperty(ref _form, value);
            }
        }

        private string _inGoodsName;
        /// <summary>
        /// 进厂运输货物名称
        /// </summary>
        [Display(Name = "进厂运输货物")]
        [StringLength(200, ErrorMessage = "{0}超长:{1}")]
        public string InGoodsName
        {
            get
            {
                return _inGoodsName;
            }
            set
            {
                SetProperty(ref _inGoodsName, value);
            }
        }

        private decimal _inGoodsVolume;
        /// <summary>
        /// 进厂运输量
        /// </summary>
        public decimal InGoodsVolume
        {
            get
            {
                return _inGoodsVolume;
            }
            set
            {
                SetProperty(ref _inGoodsVolume, value);
            }
        }

        private string _inGoodsType;
        /// <summary>
        /// 进厂物资类型
        /// </summary>
        public string InGoodsType
        {
            get
            {
                return _inGoodsType;
            }
            set
            {
                SetProperty(ref _inGoodsType, value);
            }
        }

        private string _outGoodsName;
        /// <summary>
        /// 出厂运输货物名称
        /// </summary>
        [Display(Name = "出厂运输货物")]
        [StringLength(200, ErrorMessage = "{0}超长:{1}")]
        public string OutGoodsName
        {
            get
            {
                return _outGoodsName;
            }
            set
            {
                SetProperty(ref _outGoodsName, value);
            }
        }

        private decimal _outGoodsVolume;
        /// <summary>
        /// 出厂运输量
        /// </summary>
        public decimal OutGoodsVolume
        {
            get
            {
                return _outGoodsVolume;
            }
            set
            {
                SetProperty(ref _outGoodsVolume, value);
            }
        }

        private string _outGoodsType;
        /// <summary>
        /// 出厂物资类型
        /// </summary>
        public string OutGoodsType
        {
            get
            {
                return _outGoodsType;
            }
            set
            {
                SetProperty(ref _outGoodsType, value);
            }
        }

        private string _ticketCode;
        /// <summary>
        /// 派单号
        /// </summary>
        public string TicketCode
        {
            get
            {
                return _ticketCode;
            }
            set
            {
                SetProperty(ref _ticketCode, value);
            }
        }

        private string _sendOrReceiveFlag;
        /// <summary>
        /// 收发标志
        /// </summary>
        public string SendOrReceiveFlag
        {
            get
            {
                return _sendOrReceiveFlag;
            }
            set
            {
                SetProperty(ref _sendOrReceiveFlag, value);
            }
        }

        private string _receiver;
        /// <summary>
        /// 收货单位
        /// </summary>
        public string Receiver
        {
            get
            {
                return _receiver;
            }
            set
            {
                SetProperty(ref _receiver, value);
            }
        }

        private string _sender;
        /// <summary>
        /// 发货单位
        /// </summary>
        public string Sender
        {
            get
            {
                return _sender;
            }
            set
            {
                SetProperty(ref _sender, value);
            }
        }

        /// <summary>
        /// 进厂照片
        /// </summary>
        private ObservableCollection<UploadFileItem> _inCaptureFile;
        public ObservableCollection<UploadFileItem> InCaptureFile
        {
            get { return _inCaptureFile; }
            set
            {
                SetProperty(ref _inCaptureFile, value);
            }
        }

        /// <summary>
        /// 出厂照片
        /// </summary>
        private ObservableCollection<UploadFileItem> _outCaptureFile;
        public ObservableCollection<UploadFileItem> OutCaptureFile
        {
            get { return _outCaptureFile; }
            set
            {
                SetProperty(ref _outCaptureFile, value);
            }
        }


        private Dictionary<string, CarPlateColor> _plateColorOptions;
        public Dictionary<string, CarPlateColor> PlateColorOptions
        {
            get { return _plateColorOptions; }
            set
            {
                SetProperty(ref _plateColorOptions, value);
            }
        }

        private Dictionary<string, EmissionStandard> _emissionStandardOptions;
        public Dictionary<string, EmissionStandard> EmissionStandardOptions
        {
            get { return _emissionStandardOptions; }
            set
            {
                SetProperty(ref _emissionStandardOptions, value);
            }
        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _fuelTypeOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> FuelTypeOptions
        {
            get { return _fuelTypeOptions; }
            set
            {
                SetProperty(ref _fuelTypeOptions, value);
            }
        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _truckTypeOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> TruckTypeOptions
        {
            get { return _truckTypeOptions; }
            set
            {
                SetProperty(ref _truckTypeOptions, value);
            }
        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _usageDescCodeOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> UsageDescCodeOptions
        {
            get { return _usageDescCodeOptions; }
            set
            {
                SetProperty(ref _usageDescCodeOptions, value);
            }
        }

        private List<Goods> _goodsSrouce;
        private ObservableCollection<string> _goodsOptions;
        public ObservableCollection<string> GoodsOptions
        {
            get => _goodsOptions;
            set
            {
                SetProperty(ref _goodsOptions, value);
            }
        }

        private DelegateCommand<object> _outGoodsNameSelectionChangedCmd;
        public DelegateCommand<object> OutGoodsNameSelectionChangedCmd =>
            _outGoodsNameSelectionChangedCmd ?? (_outGoodsNameSelectionChangedCmd = new DelegateCommand<object>(ExecuteOutGoodsNameSelectionChangedCmd));

        void ExecuteOutGoodsNameSelectionChangedCmd(object parameter)
        {
            ExecuteGoodsNameSelectionChanged(parameter, false);
        }

        private DelegateCommand<object> _inGoodsNameSelectionChangedCmd;
        public DelegateCommand<object> InGoodsNameSelectionChangedCmd =>
            _inGoodsNameSelectionChangedCmd ?? (_inGoodsNameSelectionChangedCmd = new DelegateCommand<object>(ExecuteInGoodsNameSelectionChangedCmd));

        void ExecuteInGoodsNameSelectionChangedCmd(object parameter)
        {
            ExecuteGoodsNameSelectionChanged(parameter, true);
        }

        private void ExecuteGoodsNameSelectionChanged(object parameter, bool inGoods)
        {
            string option = null;
            if (parameter is SelectionChangedEventArgs eventArgs)
            {
                if (eventArgs.AddedItems != null && eventArgs.AddedItems.Count > 0)
                {
                    option = eventArgs.AddedItems[0] as string;
                }
            }
            else
            {
                option = parameter as string;
            }

            if (string.IsNullOrWhiteSpace(option))
            {
                return;
            }

            var weightVal = (_goodsSrouce.FirstOrDefault(p => p.Name == option)?.DefaultWeight).GetValueOrDefault();

            if (inGoods)
            {
                InGoodsVolume = weightVal;
            }
            else
            {
                OutGoodsVolume = weightVal;
            }
        }

        private DelegateCommand _confirmImageTypeCmd;
        public DelegateCommand ConfirmImageTypeCmd =>
            _confirmImageTypeCmd ?? (_confirmImageTypeCmd = new DelegateCommand(ExecuteConfirmImageTypeCmd, CanExecuteConfirmImageTypeCmd));

        void ExecuteConfirmImageTypeCmd()
        {
            ImageTypeSelectorShow = false;
            UploadOptions.CustomerFileNameHandle = ImageTypeOptions[SelectedImageType];
            _filePicker?.ConfirmUpload();

        }

        bool CanExecuteConfirmImageTypeCmd()
        {
            return !string.IsNullOrWhiteSpace(SelectedImageType);
        }

        private DelegateCommand _openManageMeasureListDialogCmd;
        public DelegateCommand OpenManageMeasureListDialogCmd =>
            _openManageMeasureListDialogCmd ?? (_openManageMeasureListDialogCmd = new DelegateCommand(ExecuteOpenManageMeasureListDialogCmd));

        void ExecuteOpenManageMeasureListDialogCmd()
        {
            _dialogSvc.ShowDialog(nameof(ManageMeasureList), r =>
            {

            });
        }

        private DelegateCommand _saveCmd;
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSaveCmdAsync, CanExecuteSaveCmd));

        void ExecuteSaveCmdAsync()
        {
            if (!ValidateModel())
            {
                SaveCmd.RaiseCanExecuteChanged();
                AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = "提示",
                    Message = $"表单校验失败,请检查所填数据",
                    Detail = string.Join(";", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString()))
                });
                return;
            }

            Saving = true;
            SaveCmd.RaiseCanExecuteChanged();

            var formProps = _form.GetType().GetRuntimeProperties();
            var modelProps = this.GetType().GetRuntimeProperties();

            foreach (var formProp in formProps)
            {
                if (formProp.Name == nameof(_form.Id)
                    || formProp.Name == nameof(_form.CreateDate))
                {
                    continue;
                }
                ////自动开闸
                //if(formProp.Name == nameof(_form.AutoPass))
                //{
                //    _form.AutoPass = true;
                //    continue;
                //}
                var modelProp = modelProps.FirstOrDefault(p => p.Name == formProp.Name);
                if (modelProp != null)
                {
                    if (modelProp.PropertyType == typeof(AJTableFormSchemaItemOptions))
                    {
                        switch (modelProp.Name)
                        {
                            case nameof(FuelTypeCode):
                                _form.FuelTypeCode = FuelTypeCode?.Value as string;
                                _form.FuelTypeName = FuelTypeCode?.Label;
                                break;
                            case nameof(TruckTypeCode):
                                _form.TruckTypeCode = TruckTypeCode?.Value as string;
                                _form.TruckTypeName = TruckTypeCode?.Label;
                                break;
                            case nameof(UsageDescCode):
                                _form.UsageDescCode = UsageDescCode?.Value as string;
                                _form.UsageDescription = UsageDescCode?.Label;
                                break;
                            default:
                                break;
                        }
                        continue;
                    }

                    if (modelProp.PropertyType == typeof(ObservableCollection<UploadFileItem>))
                    {
                        var items = modelProp.GetValue(this) as ObservableCollection<UploadFileItem>;
                        formProp.SetValue(_form, CommonUtil.AJSerializeObject(items.Select(p => Path.GetFileName(p.Url)).ToArray()));
                        continue;
                    }

                    formProp.SetValue(_form, modelProp.GetValue(this));
                }

            }

            Saving = false;
            SaveCmd.RaiseCanExecuteChanged();

            var @params = new DialogParameters
             {
                 { "data", _form },
             };

            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, @params));
        }

        bool CanExecuteSaveCmd()
        {
            return !Saving && !HasErrors;
        }

        public string Title => string.Empty;

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public async void OnDialogOpened(IDialogParameters parameters)
        {
            parameters.TryGetValue<ShippingRecord>("data", out var data);

            var carNo = DialogTitle = data.CarNo;

            Loading = true;

            ImageTypeOptions = new Dictionary<string, Func<string>> {
                { "车头识别" ,()=> $"full_{data.CarNo}_{YitIdHelper.NextId()}"},
                { "车牌识别" ,()=> $"clip_{data.CarNo}_{YitIdHelper.NextId()}"},
                { "车身-出口监控",()=>$"monitor_{WatchPositionType.车身}_{PassagewayDirection.出}_{YitIdHelper.NextId()}" },
                { "车身-入口监控" ,()=>$"monitor_{WatchPositionType.车身}_{PassagewayDirection.进}_{YitIdHelper.NextId()}"},
                { "车头-出口监控" ,()=>$"monitor_{WatchPositionType.车头}_{PassagewayDirection.出}_{YitIdHelper.NextId()}"},
                { "车头-入口监控" ,()=>$"monitor_{WatchPositionType.车头}_{PassagewayDirection.进}_{YitIdHelper.NextId()}"}
            };

            var fuelTypeOptions = await SystemDictionaryExt.GetSystemDictionariesAsync(db, SystemDictionaryExt.SystemDictionaryKey.燃料);

            FuelTypeOptions = new ObservableCollection<AJTableFormSchemaItemOptions>(fuelTypeOptions.Select(p => new AJTableFormSchemaItemOptions
            {
                Label = p.Name,
                Value = p.Code
            }));

            var truckTypeOptions = await SystemDictionaryExt.GetSystemDictionariesAsync(db, SystemDictionaryExt.SystemDictionaryKey.货车);

            TruckTypeOptions = new ObservableCollection<AJTableFormSchemaItemOptions>(truckTypeOptions.Select(p => new AJTableFormSchemaItemOptions
            {
                Label = p.Name,
                Value = p.Code
            }));

            var usageDescCodeOptions = await SystemDictionaryExt.GetSystemDictionariesAsync(db, SystemDictionaryExt.SystemDictionaryKey.使用性质);

            UsageDescCodeOptions = new ObservableCollection<AJTableFormSchemaItemOptions>(usageDescCodeOptions.Select(p => new AJTableFormSchemaItemOptions
            {
                Label = p.Name,
                Value = p.Code
            }));

            _goodsSrouce = db.Goods.AsNoTracking().OrderByDescending(p => p.Id).ToList();

            GoodsOptions = new ObservableCollection<string>(_goodsSrouce.Select(p => p.Name));

            var _carIdentityCfg = CarIdentificationConfigExt.GetCarIdentificationConfig(db);

            var customUploadFolder = _carIdentityCfg.ImageSavePath ?? CarIdentificationConfig.GetDefaultSavePath();

            CarInfoUploadOptions.CustomUploadFolder = UploadOptions.CustomUploadFolder = customUploadFolder;
            UploadOptions.BeforeFileDialogShowHandle = (filePicker) =>
            {
                if (string.IsNullOrWhiteSpace(CarNo))
                {
                    MessageBox.Show("车牌号信息缺失", "提示", MessageBoxButton.OK);
                    return false;
                }
                _filePicker = filePicker;
                ImageTypeSelectorShow = true;
                UploadOptions.CustomUploadFolder = Path.Combine(customUploadFolder, CarNo);
                return true;
            };

            CarInfoUploadOptions.BeforeFileDialogShowHandle = (filePicker) =>
            {
                if (string.IsNullOrWhiteSpace(CarNo))
                {
                    MessageBox.Show("车牌号信息缺失", "提示", MessageBoxButton.OK);
                    return false;
                }
                CarInfoUploadOptions.CustomUploadFolder = Path.Combine(customUploadFolder, CarNo);
                return true;
            };

            if (data != null)
            {
                Form = data;

                var formProps = _form.GetType().GetRuntimeProperties();
                var modelProps = this.GetType().GetRuntimeProperties();

                foreach (var modelProp in modelProps)
                {
                    var formProp = formProps.FirstOrDefault(p => p.Name == modelProp.Name);
                    if (formProp != null)
                    {
                        if (modelProp.PropertyType == typeof(AJTableFormSchemaItemOptions))
                        {
                            switch (modelProp.Name)
                            {
                                case nameof(FuelTypeCode):
                                    FuelTypeCode = FuelTypeOptions.FirstOrDefault(p => (string)p.Value == _form.FuelTypeCode);

                                    break;
                                case nameof(TruckTypeCode):
                                    TruckTypeCode = TruckTypeOptions.FirstOrDefault(p => (string)p.Value == _form.TruckTypeCode);

                                    break;

                                case nameof(UsageDescCode):
                                    UsageDescCode = UsageDescCodeOptions.FirstOrDefault(p => (string)p.Value == _form.UsageDescCode);

                                    break;

                                default:
                                    break;
                            }
                            continue;
                        }

                        if (modelProp.PropertyType == typeof(ObservableCollection<UploadFileItem>))
                        {

                            var items = formProp.GetValue(_form) as string;
                            var array = CommonUtil.TryGetJSONObject<string[]>(items) ?? Array.Empty<string>();

                            var imagesValue = new ObservableCollection<UploadFileItem>(array.Select(p => new UploadFileItem(_carIdentityCfg.CompleteFileUrl(_form.CarNo, p))));

                            modelProp.SetValue(this, imagesValue);
                            continue;
                        }

                        modelProp.SetValue(this, formProp.GetValue(_form));
                    }
                }

            }
            else
            {
                InCaptureFile = new ObservableCollection<UploadFileItem>();
                OutCaptureFile = new ObservableCollection<UploadFileItem>();
                Attachments = new ObservableCollection<UploadFileItem>();
                VehicleLicense = new ObservableCollection<UploadFileItem>();
                CarImage = new ObservableCollection<UploadFileItem>();
                EmissionStandardImages = new ObservableCollection<UploadFileItem>();
                Nameplate = new ObservableCollection<UploadFileItem>();
                EngineNameplate = new ObservableCollection<UploadFileItem>();
                MachineEnvProtectionLabel = new ObservableCollection<UploadFileItem>();
            }

            Loading = false;
        }

        private DbService db;
        private AJGlobalExceptionResolvedEvent _globalExceptionEvt;
        private IDialogService _dialogSvc;
        private AppointAPISvc _appointAPISvc;
        private AJWPFAdmin.Core.Components.Views.AJFilePicker _filePicker;

        public ShippingRecordFormViewModel(DbService dbIns, AppointAPISvc appointAPISvc, IEventAggregator eventAggregator, IDialogService dialogSvc)
        {
            _form = new ShippingRecord();
            _appointAPISvc = appointAPISvc;
            DialogTitle = string.Empty;
            _dialogSvc = dialogSvc;
            _globalExceptionEvt = eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>();
            _globalExceptionEvt.Subscribe(() =>
            {
                Loading = Saving = false;
            });
            db = dbIns;
            UploadOptions = new UploadConfig
            {
                Limit = 6,
                Height = 120,
                Width = 120,
                Text = "上传",
                ManualUpload = true
            };
            CarInfoUploadOptions = new UploadConfig
            {
                Limit = 6,
                Height = 120,
                Width = 120,
                Text = "上传",
            };
            PlateColorOptions = CommonUtil.EnumToDictionary<CarPlateColor>(null);
            EmissionStandardOptions = CommonUtil.EnumToDictionary<EmissionStandard>(null);

        }
    }
}

